import useLocale from '@/utils/useLocale';
import React, { useEffect, useState } from 'react';
import moment from 'moment/moment';
import instance from '@/utils/request';
import { Card, Descriptions, Divider, Grid, Popover, Skeleton, Statistic, Tooltip } from '@arco-design/web-react';
import { formatMillisecondsToTime } from '@/utils/time';
import { resolveDeviceRunningStateColor } from '@/constants/functions';
import { DeviceState, DeviceStateOverview, StateGraphMinimizeView } from '@/constants/type';

const { Row, Col } = Grid;

const RuntimePanel = (props: { id: number }) => {

  interface InnerResponse extends DeviceState {
    percent: number;
  }

  const t = useLocale();
  const [loading1, setLoading1] = useState<boolean>(false);
  const [loading2, setLoading2] = useState<boolean>(false);
  const [data1, setData1] = useState<DeviceStateOverview>();
  const [data2, setData2] = useState<InnerResponse[]>([]);

  useEffect(() => {
    if (!!props.id) {
      setLoading1(true);
      instance
        .post('/api/device/stateGraph/overview', {
          deviceId: props.id,
          startTimePadding: true,
          endTimePadding: false,
          startDateTime: moment().format('YYYY-MM-DD') + ' 00:00:00',
          endDateTime: moment().add(1, 'days').format('YYYY-MM-DD') + ' 00:00:00'
        })
        .then((res) => {
          if (res.data.code === 200) {
            setData1(res.data.data);
          }
        })
        .finally(() => {
          setLoading1(false);
        });
      setLoading2(true);
      instance
        .post('/api/device/stateGraph/list', {
          deviceId: props.id,
          startTimePadding: true,
          endTimePadding: false,
          startDateTime: moment().format('YYYY-MM-DD') + ' 00:00:00',
          endDateTime: moment().add(1, 'days').format('YYYY-MM-DD') + ' 00:00:00'
        })
        .then((res) => {
          if (res.data.code === 200) {
            const total = res.data.data.map(it => it.duration).reduce((a, c) => a + c, 0);
            setData2(res.data.data.map(it => {
              return {
                ...it,
                percent: total > 0 ? it.duration * 100.0 / total : 0
              };
            }));
          }
        })
        .finally(() => {
          setLoading2(false);
        });
    }
  }, [props.id]);

  return (
    <Card>
      <Row>
        <Col span={24}>
          {!!loading1 ? (
            <Skeleton animation />
          ) : (
            <Row>
              <Col flex={1}>
                <Statistic
                  loading={loading1}
                  extra={t['global.runtime.state.total']}
                  value={data1?.totalTime}
                  renderFormat={formatMillisecondsToTime}
                  countUp
                />
              </Col>
              <Divider type="vertical" />
              <Col flex={1}>
                <Statistic
                  loading={loading1}
                  extra={t['global.runtime.state.run']}
                  value={data1?.runTime}
                  renderFormat={formatMillisecondsToTime}
                  styleValue={{ color: resolveDeviceRunningStateColor('RUN') }}
                  countUp
                />
              </Col>
              <Divider type="vertical" />
              <Col flex={1}>
                <Statistic
                  loading={loading1}
                  extra={t['global.runtime.state.stop']}
                  value={data1?.stopTime}
                  renderFormat={formatMillisecondsToTime}
                  styleValue={{ color: resolveDeviceRunningStateColor('STOP') }}
                  countUp
                />
              </Col>
              <Divider type="vertical" />
              <Col flex={1}>
                <Statistic
                  loading={loading1}
                  extra={t['global.runtime.state.idle']}
                  value={data1?.idleTime}
                  renderFormat={formatMillisecondsToTime}
                  styleValue={{ color: resolveDeviceRunningStateColor('IDLE') }}
                  countUp
                />
              </Col>
              <Divider type="vertical" />
              <Col flex={1}>
                <Statistic
                  loading={loading1}
                  extra={t['global.runtime.state.debug']}
                  value={data1?.debugTime}
                  renderFormat={formatMillisecondsToTime}
                  styleValue={{ color: resolveDeviceRunningStateColor('DEBUG') }}
                  countUp
                />
              </Col>
              <Divider type="vertical" />
              <Col flex={1}>
                <Statistic
                  loading={loading1}
                  extra={t['global.runtime.state.offline']}
                  value={data1?.offlineTime}
                  renderFormat={formatMillisecondsToTime}
                  styleValue={{ color: resolveDeviceRunningStateColor('OFFLINE') }}
                  countUp
                />
              </Col>
            </Row>
          )}
          {!!loading2 ? (
            <Skeleton style={{ marginTop: '1rem' }} animation />
          ) : (
            <Row style={{ width: '100%', marginTop: '1rem' }} justify={'center'}>
              {!!loading2 ? (
                <Skeleton />
              ) : (
                data2.map((it, idx) => {
                  return <Popover key={'tooltip_' + it.time} content={() =>
                    <Descriptions
                      column={1}
                      title={it.state}
                      data={[
                        {
                          label: '持续时间',
                          value: formatMillisecondsToTime(it.duration)
                        },
                        {
                          label: '开始时间',
                          value: idx == 0 ? moment().format('YYYY-MM-DD 00:00:00') : moment(data2[idx - 1].time).format('YYYY-MM-DD HH:mm:ss')
                        },
                        {
                          label: '结束时间',
                          value: moment(it.time).format('YYYY-MM-DD HH:mm:ss')
                        }
                      ]}
                    />
                  }>
                    <div
                      key={'device_slice_' + it.time}
                      style={{
                        display: 'inline-flex',
                        width: it.percent + '%',
                        height: '2rem',
                        background: resolveDeviceRunningStateColor(it.state)
                      }}>
                    </div>
                  </Popover>;
                })
              )}
            </Row>
          )}
        </Col>
      </Row>
    </Card>
  );
};

export default RuntimePanel;
